<template>
	<view class="cart-page qxlj_back4">
		<!-- 添加 Tabs 切换 -->
		<view class="tabs-container">
			<view class="tab-item" :class="{ active: activeTab === 0 }" @click="switchTab(0)">商品</view>
			<view class="tab-item" :class="{ active: activeTab === 1 }" @click="switchTab(1)">优惠券</view>
		</view>

		<!-- 商品列表 -->
		<view v-if="activeTab === 0">
			<car-list ref="mycar" :carList="carList" @allSelBtn="allSelBtn" @selShop="selShop" @selGoods="selGoods"
				@jsbtn="jsbtn" @delbtn="delbtn" @del="handledel"></car-list>
			<!--			<empty v-if="carList.length === 0" :isfiexd="true" title="暂无数据"></empty>-->
		</view>

		<!-- 优惠券列表 -->
		<view v-if="activeTab === 1">
			<car-list ref="mycoupon" coupons :carList="couponList" @allSelBtn="allSelBtnCoupon" @selShop="selShopCoupon"
				@selGoods="selGoodsCoupon" @jsbtn="jsbtnCoupon" @delbtn="delbtnCoupon"
				@del="handledelCoupon"></car-list>
			<!--			<empty v-if="couponList.length === 0" :isfiexd="true" title="暂无数据"></empty>-->
		</view>
	</view>
</template>


<script>
	import carList from './writeItem.vue'
	import empty from '@/components/empty.vue'
	import {
		mapMutations
	} from 'vuex'
	import {
		GetUserOrderListToBeVerified,
		PostUserOrderListToBeVerified,
		GetUserOrderListToTrendsCode,
		PostUserVerifyCoupons
	} from '@/api/mall.js'
	import {
		getweixinUserInfo,
	} from '@/api/homePage.js';
	export default {
		name: "carPage",
		components: {
			carList,
			empty,
		},
		data() {
			return {
				activeTab: 0, // 当前激活的标签页 0-商品 1-优惠券
				maskTitle: '',
				carList: [],
				couponList: [], // 优惠券列表
				uniApp: '',
				CustomerOpneid: '',
				BusinessOpenid: '',
			};
		},
		onLoad(options) {
			console.log(options, options.q)
			const urlStr = decodeURIComponent(options.q)
			console.log(urlStr)
			let url = ''
			if (typeof urlStr == "undefined") {
				url = decodeURI(location.search); //获取url中"?"符后的字符串
			} else {
				url = "?" + urlStr.split("?")[1];
			}
			let params = {};
			if (url.indexOf("?") != -1) {
				let str = url.substr(1);
				let strs = str.split("&");
				for (let i = 0; i < strs.length; i++) {
					params[strs[i].split("=")[0]] = decodeURI(strs[i].split("=")[1]);
				}
			}
			console.log("params = ", params)
			if (params.CustomerOpneid) {
				this.CustomerOpneid = params.CustomerOpneid;
			}
			this.uniApp = uni.getAccountInfoSync().miniProgram.appId;
			this.checkLogin();
		},
		methods: {
			// 切换标签页
			switchTab(index) {
				console.log(index)
				this.activeTab = index;
				// 如果切换到优惠券标签且优惠券列表为空，则加载优惠券数据
				if (index === 1 && this.couponList.length === 0) {
					this.loadCouponData();
				}
				// 更新列表统计数据
				this.$nextTick(() => {
					if (index === 0 && this.$refs.mycar) {
						this.$refs.mycar.getAllMount();
					} else if (index === 1 && this.$refs.mycoupon) {
						this.$refs.mycoupon.getAllMount();
					}
				});
			},

			async checkLogin() {
				const token = uni.getStorageSync('token');
				console.log(token)
				//if (token == '' || token == null){
				let that = this;
				uni.login({
					provider: 'weixin',
					success: function(loginRes) {
						console.log("获取用户信息")
						// 获取用户信息
						uni.getUserInfo({
							provider: 'weixin',
							success: function(infoRes) {
								console.log(infoRes)
								var Data = {
									appid: that.uniApp,
									userInfo: infoRes.userInfo,
									encryptedData: infoRes.encryptedData,
									iv: infoRes.iv,
									rescode: loginRes.code
								}
								that.getUserMsg(Data)
							}
						});
					}
				});
				//	}
			},
			async getUserMsg(code) {
				try {
					const {
						ErrorCode,
						Msg,
						Data
					} = await getweixinUserInfo(
						code
					);
					//const Data = config.testUserInfo.Data;
					if (Data) {
						uni.setStorageSync('token', Data.user_token);
						uni.setStorageSync('userInfo', Data.wxUser);
						uni.setStorageSync('userMemberTags', Data.userMemberTags)
						this.BusinessOpenid = Data.wxUser.OpenId;
						this.loadData();
					} else {
						this.$api.msg('获取token失败');
					}
				} catch (e) {
					console.log("getUserMsg", e)
				}
			},
			...mapMutations(['setGoodsInfoList']),
			async loadData() {
				try {
					const {
						Data
					} = await GetUserOrderListToBeVerified({
						BusinessOpenid: this.BusinessOpenid,
						CustomerOpneid: this.CustomerOpneid,
						Index: 1,
						Size: 100,
					})

					console.log(666, Data)
					Data.forEach(con => {
						con['selected'] = true;
					})
					this.carList = Data;

					this.$nextTick(function() {
						if (this.$refs.mycar) {
							this.$refs.mycar.getAllMount(); //计算价格展示
						}
					})
				} catch (e) {
					console.log(this.BusinessOpenid)
					console.log(this.CustomerOpneid)
					console.log("loadData", e)
					this.$api.msg(e.Msg + '正在跳转首页', 2000)
					// setTimeout(() => {
					// 	uni.redirectTo({
					// 		url: '/pages/center/index?index=1',
					// 	})
					// }, 2000)
					this.loadingType = 'nomore'
					//TODO handle the exception
				}
			},

			// 加载优惠券数据
			async loadCouponData() {
				try {
					uni.showLoading({
						title: '加载中...'
					});

					const {
						Data
					} = await GetUserOrderListToTrendsCode({
						BusinessOpenid: this.BusinessOpenid,
						CustomerOpneid: this.CustomerOpneid,
						Index: 1,
						Size: 100,
					})

					console.log('优惠券数据:', Data);
					Data.forEach(con => {
						con['selected'] = true;
					})
					this.couponList = Data;

					uni.hideLoading();

					this.$nextTick(() => {
						if (this.$refs.mycoupon) {
							this.$refs.mycoupon.getAllMount(); //计算价格展示
						}
					})
				} catch (e) {
					uni.hideLoading();
					console.log("loadCouponData", e);
					this.$api.msg(e.Msg || '加载优惠券列表失败');
				}
			},

			async handledel(carList) {
				try {
					let arr = [];
					carList.forEach(con => {
						let obj = {
							ProductOrdersCouponInfoCode: con.Code,
							OrdersCouponId: con.OrdersCouponId,
							UsersId: '',
							OrdersOnLineId: con.OrdersOnLineId,
							OrdersOnLineType: con.OrdersOnLineType
						};
						arr.push(obj)
					})
					const {
						Data
					} = await PostUserOrderListToBeVerified(arr);
					console.log(Data)
					this.$api.msg('核销成功')
					const newArray = this.carList.filter(item1 =>
						!carList.some(item2 => item1.OrdersCouponId === item2.OrdersCouponId)
					);
					this.carList = newArray;
					// this.loadData()
				} catch (e) {
					console.log(e)
					//TODO handle the exception
				}
			},

			// 优惠券核销
			async handledelCoupon(couponList) {
				console.log(couponList)
				try {
					if (this.activeTab === 0) {
						let arr = [];
						couponList.forEach(con => {
							let obj = {
								ProductOrdersCouponInfoCode: con.Code,
								OrdersCouponId: con.OrdersCouponId,
								UsersId: '',
								OrdersOnLineId: con.OrdersOnLineId,
								OrdersOnLineType: con.OrdersOnLineType
							};
							arr.push(obj)
						})
						const {
							Data
						} = await PostUserOrderListToBeVerified(arr);
						console.log(Data)
						const newArray = this.couponList.filter(item1 =>
							!couponList.some(item2 => item1.OrdersCouponId === item2.OrdersCouponId)
						);
						this.couponList = newArray;
					} else {
						console.log(this.couponList)
						const {
							Data
						} = await PostUserVerifyCoupons(couponList.map(item => item.Id))
						const newArray = this.couponList.filter(item1 =>
							!couponList.some(item2 => item1.Id === item2.Id)
						);
						this.couponList = newArray;
					}

					this.$api.msg('核销成功')

				} catch (e) {
					console.log(e)
					this.$api.msg(e.Msg || '核销失败')
				}
			},

			selGoods: function(carList) {
				var that = this;
				that.carList = carList;
			},
			selShop: function(carList) {
				var that = this;
				that.carList = carList;
			},
			allSelBtn: function(carList) {
				var that = this;
				that.carList = carList;
			},

			// 优惠券选择事件处理
			selGoodsCoupon: function(couponList) {
				var that = this;
				that.couponList = couponList;
			},
			selShopCoupon: function(couponList) {
				var that = this;
				that.couponList = couponList;
			},
			allSelBtnCoupon: function(couponList) {
				var that = this;
				that.couponList = couponList;
			},

			jsbtn: function(carList) {
				// 一键核销
				let that = this;
				uni.showModal({
					title: '提示',
					content: '是否一键核销当前选中商品?',
					confirmColor: '#498FFF',
					success: function(res) {
						if (res.confirm) {
							that.handledel(carList)
						} else if (res.cancel) {}
					}
				});
			},

			// 优惠券核销按钮
			jsbtnCoupon: function(couponList) {
				// 一键核销
				let that = this;
				uni.showModal({
					title: '提示',
					content: '是否一键核销当前选中优惠券?',
					confirmColor: '#498FFF',
					success: function(res) {
						if (res.confirm) {
							that.handledelCoupon(couponList)
						} else if (res.cancel) {}
					}
				});
			},

			// 占位方法，保持与商品列表相同的接口
			delbtnCoupon: function() {},
		},
		onShareAppMessage() {

		}
	}
</script>

<style lang="scss" scoped>
	* {
		background-color: #e9e9e9;
	}

	.cart-page {
		//padding-bottom: 100rpx;
		background-color: #F0F4F3;
		min-height: 100vh;
		padding: 20rpx 20rpx 100rpx 20rpx;
	}

	.tabs-container {
		display: flex;
		background-color: #ffffff;
		border-radius: 10rpx;
		margin-bottom: 20rpx;
		overflow: hidden;
		box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
	}

	.tab-item {
		flex: 1;
		height: 80rpx;
		line-height: 80rpx;
		text-align: center;
		font-size: 28rpx;
		color: #666;
		background-color: #ffffff;
		position: relative;
	}

	.tab-item.active {
		color: #498FFF;
		font-weight: bold;
		background-color: #ffffff;
	}

	.tab-item.active::after {
		content: '';
		position: absolute;
		left: 50%;
		bottom: 0;
		transform: translateX(-50%);
		width: 60rpx;
		height: 4rpx;
		background-color: #498FFF;
		border-radius: 2rpx;
	}
</style>